package com.czh.gzskzn.shenke3;


import android.app.ActionBar;
import android.app.Activity;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.czh.gzskzn.shenke3.FragmentX.ReMenFargment;
import com.czh.gzskzn.shenke3.FragmentX.TeJiaFargment;
import com.czh.gzskzn.shenke3.QianFagment.FragmentPage1;
import com.czh.gzskzn.shenke3.QianFagment.FragmentPage2;
import com.czh.gzskzn.shenke3.Util.ImagePaperAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by gzsk on 2017/4/18.
 * name  陈忠红
 * email czhhx15599109256@163.com
 */

public class WaiMaiFrag extends Fragment implements View.OnClickListener{
    private View view;
    private ViewPager mPaper;
    private FragmentPagerAdapter mAdapter;
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private TextView tv_footable,tv_midfield,tv_forward,tv_guard;

    private ViewPager mviewPager;
    /**用于小圆点图片*/
    private List<ImageView> dotViewList;
    /**用于存放轮播效果图片*/
    private List<ImageView> list;

    private LinearLayout dotLayout;
    private ImageButton imageButton;
    private int currentItem  = 0;//当前页面

    boolean isAutoPlay = true;//是否自动轮播

    private ScheduledExecutorService scheduledExecutorService;

    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if(msg.what == 150){
                mviewPager.setCurrentItem(currentItem);
            }
        }

    };

    private Display display;
    private int itemWidth;
    private GridView gridView_newVideo,gridView_hotVideo;

//    下面切换
//      热门
    private ReMenFargment reMenFargment;
//      特价
    private TeJiaFargment teJiaFargment;
//    控件
    private TextView reMei,teSe;
    private FragmentManager fragmentManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.weimaifrag,
                container, false);
        initLayout();


        /*************         轮播      **********/

//        inflater = LayoutInflater.from(getActivity());
        mviewPager = (ViewPager) view.findViewById(R.id.wei_myviewPager);
        dotLayout = (LinearLayout)view.findViewById(R.id.wei_dotLayout);
        dotLayout.removeAllViews();
        initView();
        if(isAutoPlay){
            startPlay();
        }
        fragmentManager = getFragmentManager();
        // 第一次启动时选中第0个tab
        setTabSelection(0);

        return view;
    }


    /**
     * 初始化控件
     */
    public void initLayout(){
        reMei = (TextView)view.findViewById(R.id.tv_reMen);
        teSe = (TextView)view.findViewById(R.id.tv_Teshu);

        reMei.setOnClickListener(this);
        teSe.setOnClickListener(this);


        FragmentPage1 f1 = new FragmentPage1();
        FragmentPage2 f2 = new FragmentPage2();
        mFragments.add(f1);
        mFragments.add(f2);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.tv_reMen:
            setTabSelection(0);

                break;
            case R.id.tv_Teshu:
            setTabSelection(1);
                break;


        }

    }

    /**
     * ViewPager适配器
     */
    public class MyPagerAdapter extends PagerAdapter {
        public List<Activity> mListViews;

        public MyPagerAdapter(List<Activity> mListViews) {
            this.mListViews = mListViews;
        }


        @Override
        public void finishUpdate(View arg0) {
        }

        @Override
        public int getCount() {
            return mListViews.size();
        }



        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == (arg1);
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }
    }

    /**
     * 轮播
     * */
    private void initView() {

        dotViewList = new ArrayList<ImageView>();
        list = new ArrayList<ImageView>();


        for (int i = 0; i < 4; i++) {
            ImageView dotView = new ImageView(getActivity());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ActionBar.LayoutParams(
                    ActionBar.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));

            params.leftMargin = 15;//设置小圆点的外边距
            params.rightMargin = 15;

            params.height = 25;//设置小圆点的大小
            params.width = 25;

            if(i == 0){
                dotView.setBackgroundResource(R.drawable.point_pressed);
            }else{

                dotView.setBackgroundResource(R.drawable.point_unpressed);
            }
            dotLayout.addView(dotView, params);

            dotViewList.add(dotView);
            //上面是动态添加了四个小圆点
        }


        ImageView img1 = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.scroll_vew_item1, null);
        ImageView img2 = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.scroll_vew_item1, null);
        ImageView img3 = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.scroll_vew_item1, null);
        ImageView img4 = (ImageView) LayoutInflater.from(getActivity()).inflate(R.layout.scroll_vew_item1, null);

        img1.setBackgroundResource(R.drawable.banner1);
        img2.setBackgroundResource(R.drawable.main_img1);
        img3.setBackgroundResource(R.drawable.main_img2);
        img4.setBackgroundResource(R.drawable.main_img3);

        list.add(img1);
        list.add(img2);
        list.add(img3);
        list.add(img4);

        img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(),"asasasas",Toast.LENGTH_SHORT).show();
            }
        });

        ImagePaperAdapter adapter = new ImagePaperAdapter((ArrayList)list);

        mviewPager.setAdapter(adapter);
        mviewPager.setCurrentItem(0);
        mviewPager.setOnPageChangeListener(new WaiMaiFrag.MyPageChangeListener());

    }
    /**
     * 开始轮播图切换
     */
    private void startPlay(){
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new WaiMaiFrag.SlideShowTask(), 1, 4, TimeUnit.SECONDS);
        //根据他的参数说明，第一个参数是执行的任务，第二个参数是第一次执行的间隔，第三个参数是执行任务的周期；
    }

    /**
     *执行轮播图切换任务
     *
     */
    private class SlideShowTask implements Runnable{

        @Override
        public void run() {
            // TODO Auto-generated method stub
            synchronized (mviewPager) {
                currentItem = (currentItem+1)%list.size();
                handler.sendEmptyMessage(150);
            }
        }
    }

    /**
     * ViewPager的监听器
     * 当ViewPager中页面的状态发生改变时调用
     *
     */
    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {

        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub
            switch (arg0) {
                case 1:// 手势滑动，空闲中
                    isAutoPlay = false;
                    System.out.println(" 手势滑动，空闲中");
                    break;
                case 2:// 界面切换中
                    isAutoPlay = true;
                    System.out.println(" 界面切换中");
                    break;
                case 0:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (mviewPager.getCurrentItem() == mviewPager.getAdapter().getCount() - 1 && !isAutoPlay) {
                        mviewPager.setCurrentItem(0);
                        System.out.println(" 滑动到最后一张");
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (mviewPager.getCurrentItem() == 0 && !isAutoPlay) {
                        mviewPager.setCurrentItem(mviewPager.getAdapter().getCount() - 1);
                        System.out.println(" 滑动到第一张");
                    }
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onPageSelected(int pos) {
            // TODO Auto-generated method stub
            //这里面动态改变小圆点的被背景，来实现效果
            currentItem = pos;
            for (int i = 0; i < dotViewList.size(); i++) {
                if (i == pos) {
                    ((View) dotViewList.get(pos)).setBackgroundResource(R.drawable.point_pressed);
                } else {
                    ((View) dotViewList.get(i)).setBackgroundResource(R.drawable.point_unpressed);
                }
            }
        }
    }
    private void setTabSelection(int index) {
        // 每次选中之前先清楚掉上次的选中状态
        clearSelection();
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case 0:
                // 当点击了首页tab时，改变控件的图片和文字颜色
//                messageImage.setImageResource(R.drawable.home_white);
                reMei.setTextColor(Color.parseColor("#FF0C97FF"));
                if (reMenFargment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    reMenFargment = new ReMenFargment();
                    transaction.add(R.id.content1, reMenFargment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(reMenFargment);
                }
                break;
            case 1:
                // ，改变控件的图片和文字颜色
                teSe.setTextColor(Color.parseColor("#FF0C97FF"));
                if (teJiaFargment == null) {
                    // 如果ContactsFragment为空，则创建一个并添加到界面上
                    teJiaFargment = new TeJiaFargment();
                    transaction.add(R.id.content1, teJiaFargment);
                } else {
                    // 如果ContactsFragment不为空，则直接将它显示出来
                    transaction.show(teJiaFargment);
                }
                break;

        }
        transaction.commit();
    }
    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (reMenFargment != null) {
            transaction.hide(reMenFargment);
        }
        if (teJiaFargment != null) {
            transaction.hide(teJiaFargment);
        }
    }
    private void clearSelection() {

        reMei.setTextColor(Color.parseColor("#82858b"));

        teSe.setTextColor(Color.parseColor("#82858b"));
    }


}
